<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\Http\model\Sms;
use App\Http\model\Curdpost;
/**
* 定单控制器
*/
class SorderController extends Controller
{

	/**
	 * 历史乘车人
	 */
	public function historyCar(Request $request)
	{
		$uid = $request->get('id'); //司机id
		$re = Db :: table('order')
				->leftJoin('order_extend','order.extendid','=','order_extend.id')
				->where('uid',$uid)
				->select('order_extend.passenger_name','order_extend.passenger_phone')
				->get();
		$re = json_decode(json_encode($re),true);
		$arr['data'] = $re;
		$arr['code'] = '1000';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
	/** 
	 * 取汉字的第一个字的首字母 
	 * @param type $str 
	 * @return string|null 
	 */  
	public function _getFirstCharter($str){  
	    if(empty($str)){
	    	return '';
	    }
	    $fchar=ord($str{0});
	    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
	    $s1=iconv('UTF-8','gb2312',$str);
	    $s2=iconv('gb2312','UTF-8',$s1);
	    $s=$s2==$str?$s1:$str;
	    $asc=ord($s{0})*256+ord($s{1})-65536;
	    if($asc>=-20319&&$asc<=-20284) return 'A';
	    if($asc>=-20283&&$asc<=-19776) return 'B';
	    if($asc>=-19775&&$asc<=-19219) return 'C';
	    if($asc>=-19218&&$asc<=-18711) return 'D';
	    if($asc>=-18710&&$asc<=-18527) return 'E';
	    if($asc>=-18526&&$asc<=-18240) return 'F';
	    if($asc>=-18239&&$asc<=-17923) return 'G';
	    if($asc>=-17922&&$asc<=-17418) return 'H';
	    if($asc>=-17417&&$asc<=-16475) return 'J';
	    if($asc>=-16474&&$asc<=-16213) return 'K';
	    if($asc>=-16212&&$asc<=-15641) return 'L';
	    if($asc>=-15640&&$asc<=-15166) return 'M';
	    if($asc>=-15165&&$asc<=-14923) return 'N';
	    if($asc>=-14922&&$asc<=-14915) return 'O';
	    if($asc>=-14914&&$asc<=-14631) return 'P';
	    if($asc>=-14630&&$asc<=-14150) return 'Q';
	    if($asc>=-14149&&$asc<=-14091) return 'R';
	    if($asc>=-14090&&$asc<=-13319) return 'S';
	    if($asc>=-13318&&$asc<=-12839) return 'T';
	    if($asc>=-12838&&$asc<=-12557) return 'W';
	    if($asc>=-12556&&$asc<=-11848) return 'X';
	    if($asc>=-11847&&$asc<=-11056) return 'Y';
	    if($asc>=-11055&&$asc<=-10247) return 'Z';
	    return null;
	}   
	/**
	 * 服务城市
	 */
	public function serCity(Request $requset)
	{
		$city = Db :: table('cost')->select('city')->get();
		$city = json_decode(json_encode($city),true);
		$cityArr = [];
		if(!empty($city)){
			//将二维数组处理为一维数组
			$array = [];
			foreach ($city as $key => $value) {
				$array[] = $value['city'];
			}
			$str='';
			for ($i=0; $i < count($array); $i++) { 
				if($i<count($array)-1){
					$str = $array[$i] .',' .$str ;
				}else{
					$str = $str.$array[$i];
				}
			}
			$array2 = explode(',', $str);
			$cty = Db :: table('region')->whereIn('code',$array2)->select('fullName','code')->get();
			$cty = json_decode(json_encode($cty),true);
			$zmArr = [];
			foreach ($cty as $key => &$value) {
				$value['code'] = (string)$value['code'];
				//将数组存入字母数组
				$zm = $this->_getFirstCharter($value['fullName']);
				$zmArr[$zm][] = $value;
			}
			ksort($zmArr);
			$arr['data'] = $zmArr;
			$arr['code'] = '1000';
			$arr['msg'] = '请求成功';
		}else{
			$arr['data'] = '';
			$arr['code'] = '1001';
			$arr['msg'] = '暂无服务城市';
		}
		return json_encode($arr);
	}
	/**
	 * 车系选择
	 * 服务类型
	 * 城市
	 */
	public function choseCar(Request $requset)
	{
		$types = $requset['types'];//即时用车
		$cityCode = Db :: table('region')->where('fullName',$requset['city'])->first();
		$cityCode = $cityCode -> code;//区域标号110100
		//拿取服务类型id
		$typesId = Db :: table('server_item')->where('name',$types)->select('id')->first();

		//拿到该服务类型下面所有的服务城市和对应的车系
		$re = Db :: table('cost')->where('sername',$typesId->id)->select('city','serid')->get();
		$re = json_decode(json_encode($re),true);
		$carser = [];
		if(!empty($re)){
			foreach ($re as $key => $value) {
				$valueArr = explode(',',$value['city']);
				if(in_array($cityCode,$valueArr)){
					$carser[] = $value['serid'];
				}
			}
			if(!empty($carser)){
				$car = Db :: table('car_series')
						->whereIn('id',$carser)->where('isdel',1)->select('id','name','pic')->get();
				$car = json_decode(json_encode($car),true);	
				$arr['data'] = $car;

				$arr['code'] = '1000';
				$arr['msg'] = '请求成功';
			}else{
				$arr['data'] = '';
				$arr['code'] = '1001';
				$arr['msg'] = '暂无车系';
			}
		}else{
			$arr['data'] = '';
			$arr['code'] = '1001';
			$arr['msg'] = '暂无车系';
		}
		return json_encode($arr);
		
	}
	/**
	 * 计算价格
	 * $ori  string 起点经纬度
	 * $des  string 终点经纬度
	 * $types '即时用车'
	 * $carid 车系id
	 * $areaid 城市id
	 * $usetime 用车时间 2017-04-23 13:22
	 */
	public function chargePrice(Request $requset)
	{
		$ori = explode(',',$requset['ori']);
		$orig = $ori[1] . ',' . $ori[0];
		$des = explode(',',$requset['des']);
		$dest = $des[1] . ',' . $des[0];
		$types = $requset['types'];
		$carid = $requset['carid'];
		$cityCode = Db :: table('region')->where('fullName',$requset['city'])->first();
		$areaid = $cityCode -> code;//区域标号110100
		//$areaid = $requset['areaid'];
		$usetime = $requset['usetime'];
		$re = $this->price($orig, $dest,$types, $usetime, $carid, $areaid);
		return json_encode($re);

	}
	/**
	 * 下单
	 */
	public function setOrder(Request $requset)
	{
		
		$uid = $requset -> get('id');//用户id
		$jiesuanstatus = Db :: table('order')
							->where('uid',$uid)->where('jiesuanstatus',1)->select('id')->first();
		$jiesuanstatus = json_decode(json_encode($jiesuanstatus),true);	
		if(!empty($jiesuanstatus)){
			$arr = [
				'data'=>[
					'id'=>$jiesuanstatus['id']
				],
				'code'=>'1001',
				'msg'=>'有订单尚未结算'
			];
			return json_encode($arr);
		}
		$price = $requset['price'];//订单价格
		$isCanPay = Db :: table('social_user')
						->where('id',$uid)->where('sum_money','>',$price)
						->select('nickname','phone','created_at','sex')->first();
		$isCanPay = json_decode(json_encode($isCanPay),true);	
		if(empty($isCanPay)){
			$arr = [
				'data'=>[
					
				],
				'code'=>'1002',
				'msg'=>'余额不足'
			];
			return json_encode($arr);
		}
		//订单号
		$num = date('ymds') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 7);
		//是否本人乘车1是，2不是
		if ($requset['isSelf'] == 1) {
			$people = $isCanPay['nickname'];
			$phone =  $isCanPay['phone'];
		}else{
			$people = $requset['people'];//乘车人姓名
			$phone = $requset['phone'];//乘车人电话
		}
		//查订单类型id
		$typeName = $requset['typeName'];//即时用车 
		$serTypeId = Db :: table('server_item')->where('name',$typeName)->select('id')->first();
		$typeid = $serTypeId -> id;
		//订单扩展表数组
		$extendArr = [
			'passenger_name'=>$people,
			'passenger_phone'=>$phone,
			'type'=>2,
		];
		$cityCode = Db :: table('region')->where('fullName',$requset['city'])->first();
		$areaid = $cityCode -> code;//区域标号110100
		//订单表数组
		$orderArr = [
			'uid'=>$uid,
			'num'=>$num,
			'typeid'=>$typeid,
			'original'=>$requset['original'],//上车地址
			'end'=>$requset['end'],//下车地
			'originaldegree'=>$requset['originaldegree'],//上车地点经纬度
			'enddegree'=>$requset['enddegree'],//下车地点经纬度
			'usetime'=>strtotime($requset['usetime']),//用车时间
			'createtime'=>date('Y-m-d H:i:s',time()),
			'status'=>1,
			'source'=>5,
			'jiesuanstatus'=>1,
			'orderstatus'=>1,
			'implementstatus'=>1,
			'charging'=>1,
			'sumpeople'=>$requset['sumpeople'],//乘车人数
			'areacode'=>$areaid,//区域code
			'beizhu'=>$requset['beizhu'],//乘客备注
			'carserid'=>$requset['carserid']
		];
		//订单里程时间数组
		$originaldegree = explode(',',$requset['originaldegree']);
		$or = $originaldegree[1].','.$originaldegree[0];
		$enddegree = explode(',',$requset['enddegree']);
		$en = $enddegree[1].','.$enddegree[0];
		$ddis = $this->countdis($or,$en);
		//dump($ddis);
		$orderLong = [
			'prelong'=>$ddis['data2'][0]['distance'],
			'pretime'=>$ddis['data2'][0]['time'] / 60
		];
		//订单价格数组
		$orderPrice= [
			'serprice'=>$price,
			'preprice'=>$price,
			'jsj'=>2,
		];
		//订单状态数组
		$orderStatus = [
			'order_number'=>$num,
			'status'=>1,
			'update_time'=>time()
		];
		//订单评价数组
		$orderThought = [
			'num'=>$num,
			'create_time'=>time()
		];
		 DB::beginTransaction();
		 try {
		 	//写入订单扩展表
		 	$extendid = Db :: table('order_extend')->insertGetId($extendArr);
		 	//订单扩展表id
		 	$orderArr['extendid'] = $extendid;
		 	//写入订单表
		 	$orderId = Db :: table('order')->insertGetId($orderArr);
		 	//写入订单里程表
		 	$orderLong['oid'] = $orderId;
		 	Db :: table('order_long')->insert($orderLong);
		 	//写入订单价格表
		 	$orderPrice['oid'] = $orderId;
		 	Db :: table('order_price')->insert($orderPrice);
		 	//写入订单状态表
		 	Db :: table('order_status')->insert($orderStatus);
		 	//写入订单评价表
		 	Db :: table('thought')->insert($orderThought);
		 	//扣除预付款
		 	Db :: table('social_user')->where('id',$uid)->decrement('sum_money',$price);
		 	DB::commit();
		 } catch (Exception $e) {
		 	DB::rollBack();
		 	$arr = [
				'info'=>$e,
				'code'=>'1003',
				'msg'=>'数据库操作错误'
			];
			return json_encode($arr);
		 }
		 if($requset['sendSms'] == 1){//发短信
		 	 $msg = '您预订'.$requset['usetime'].'的'.$requset['typeName'].'订单下单成功，稍后将有专属司机为您服务。【时代出行】';
	        $code = new Sms();
	        $code -> sendSMS($phone,$msg);
		 }
		 //同步到网约车数据库
		 $IntenetDb = new Curdpost();
		 //订单发起数据表
		 $table = 'ordercreate';
		 //上车地点经纬度转为数组
		 $InteOri = explode(',',$requset['originaldegree']);
		 //下车地点经纬度转为数组
		 $InteEnd = explode(',',$requset['enddegree']);
		 $tableCont = [
		 	'CompanyId'=>'test',
		 	'Address'=>$areaid,
		 	'OrderId'=>$num,
		 	'DepartTime'=>date('YmdHis',strtotime($requset['usetime'])),
		 	'OrderTime'=>date('YmdHis',time()),
		 	'PassengerNote'=>$requset['beizhu'],
		 	'Departure'=>$requset['original'],
		 	'DepLongitude'=> $InteOri[0],
		 	'DepLatitude'=>$InteOri[1],
		 	'Destination'=>$requset['end'],
		 	'DestLongitude'=>$InteEnd[0],
		 	'DestLatitude'=>$InteEnd[1],
		 	'Encrypt'=>'3',
		 	'FareType'=>'13211'
		 ];
		
		 //写入乘客基本信息表
		 $tableU = 'passenger';
		 if($isCanPay['sex'] == 1){
		 	$sex = '男';
		 }else{
		 	$sex = '女';
		 }
		 $Ucont = [
		 	'CompanyId'=>'test',
		 	'RegisterDate'=>date('YmdHis',strtotime($isCanPay['created_at'])),
		 	'PassengerPhone'=>$phone,
		 	'PassengerName'=>$people,
		 	'PassengerGender'=>$sex,
		 	'State'=>0,
		 	'Flag'=>1,
		 	'UpdateTime'=>date('TmdHis',time())
		 ];
		 try {
		 	//写入订单发起数据表
		 	$IntenetDb -> NewInsert($table,$tableCont);
		 	//写入乘客基本信息表
		 	$IntenetDb -> NewInsert($tableU,$Ucont);
		 } catch (Exception $e) {
		 	$arr = [
			 	'info'=>$e,
			 	'code'=>'1004',
			 	'msg'=>'网约车数据库同步失败'
		 	];
		 	return json_encode($arr);
		 }
		 $arr = [
		 	'id'=>$orderId,
		 	'code'=>'1000',
		 	'msg'=>'下单成功'
		 ];
		 return json_encode($arr);
		 
	}
	/*
		$ori  起点
		$des 终点
		计算两点之间的距离
	*/
	private function countdis($ori,$des)
	{
		//$ori = '39.916566441207,116.47672599552|40.047452206531,116.44685440027';
		//$des = '40.086792,116.594566';
		$url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $ori . '&destinations=' . $des . '&ak=RGwhFRkSZfva32BN96csoObm4FIfiCAY';
		$re = $this->get_curl_json($url);
		
		if($re['status'] == 0){
			$arr['code'] = '200';
			$arr['msg'] = '请求成功';
			$i = 0;
			foreach ($re['result'] as $key => $value) {
				$arr['data'][$i]['distance'] = $value['distance']['text'];
				$arr['data'][$i]['time'] = $value['duration']['text'];
				$arr['data2'][$i]['distance'] = $value['distance']['value'];
				$arr['data2'][$i]['time'] = $value['duration']['value'];
				$i++;
			}
		}else{
			$arr['code'] = '500';
			$arr['msg'] = '百度服务器错误';
			$arr['data'] = '';
		}
		return $arr;
	}
	/**
	 * 计算价格
	 * $origins  string 起点纬经
	 * $destinations   string 终点纬经
	 * $types '即时用车'
	 * $carid 车系id
	 * $areaid 城市id
	 * $usetime 用车时间 2017-04-23 13:22
	 */
	private function price($origins, $destinations,$types, $usetime, $carid, $areaid)
	{
		
        $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $origins . '&destinations=' . $destinations . '&ak=RGwhFRkSZfva32BN96csoObm4FIfiCAY';
        // return  $url;
        $result = $this->get_curl_json($url);
       // dump($result);
        $time = round($result['result'][0]['duration']['value'] / 60);//时间
        $return['time'] = $time;
       // dump($time);
        $dis = round($result['result'][0]['distance']['value']/1000, 1);//距离
        $return['dis'] = $dis;
       // dump($dis);
        $return = [];
        $price = 0;
        $typesId = Db :: table('server_item')->where('name',$types)->select('id')->first();
        $re = Db:: table('cost')
        		->where('sername',$typesId->id)->where('serid',$carid)->select('id','city')->get();
        $re = json_decode(json_encode($re),true);	
        //dump($re);
        $historyId = '';
        if(!empty($re)){
        	foreach ($re as $key => $value) {
        		$valueArr = explode(',',$value['city']);
        		if(in_array($areaid,$valueArr)){
        			 $historyId = $value['id'];
        			 continue;
        		}
        	}
        	if( $historyId == ''){
        		$return['price'] = 0;
	            $return['msg'] = '没有该服务';
	            $return['code'] = '1001';
	            return $return;
        	}
        }else{
        	$return['price'] = 0;
            $return['msg'] = '没有该服务';
            $return['code'] = '1001';
            return $return;
        }
       	$algorithmid = Db :: table('history_algorithm')
       						->where('costid',$historyId)
       						->orderBy('id','desc')->select('algorithmid')->first();
       	$algorithmid = json_decode(json_encode($algorithmid),true);
       	if(empty($algorithmid)){
       		$return['price'] = 0;
            $return['msg'] = '没有该服务';
            $return['code'] = '1001';
            return $return;
       	}
       	$algorithmidStr = $algorithmid['algorithmid'];
       	$re = Config::get('charge.'.$algorithmidStr);
        if (!empty($re)) {
            $difdis = $dis - $re['basis_km'];//实际距离与后台设置距离差
            //dump($difdis);
            if ($difdis > 0) {//实际距离大
                $difdis2 = $dis - $re['super_km_km'];//超过多少公里以后
               // dump($difdis2);
                if ($difdis2 < $re['super_km_shortage_km']) {//不做多少公里不计费
                    $price = $re['price'];
                    //dump($price);
                } else {//计算白天和夜间的超公里收费
                    $usetime1 = explode(' ', $usetime);
                    $usetime2 = strtotime($usetime);
                    $day_start_time = strtotime($usetime1[0] . $re['day_start_time']);
                    $day_end_time = strtotime($usetime1[0] . $re['day_end_time']);
                    $avgdis = $difdis2 / $re['super_km_per_km'];
                   // dump($avgdis);
                    if ($day_start_time < $usetime2 && $usetime2 < $day_end_time) {
                        $price = $re['price'] + $avgdis * $re['day_commission'];
                        //dump($price);
                    } else {
                        $price = $re['price'] + $avgdis * $re['night_commission'];
                    }
                }
            } else {//实际距离小
                $price = $re['price'];
            }
            $diftime = $time - $re['basis_time'];
            //dump($diftime);
            if ($diftime > 0) {//超时
                $diftime2 = $time - $re['starting_starting_time'];//起步后多少分钟内不收费
                if ($diftime2 < 0) {
                    $price = $price;
                } else {
                    $diftime3 = $diftime2 - $re['starting_shortage_time'];
                    if ($diftime3 < 0) {
                        $price = $price;
                    } else {
                        if($re['starting_exceed_time'] > 0){
                            $avgtime = $diftime3 / $re['starting_exceed_time'];
                        }else{
                            $avgtime = $diftime3;
                        }
                        
                        $price = $price + $avgtime * $re['starting_add_money'];
                    }
                }
            } else {//不超时
                $price = $price;
                //dump($price);
            }
            $return['price'] = sprintf("%.2f",$price); 
            $return['msg'] = 'success';
            $return['code'] = '1000';
        } else {
            $return['price'] = 0;
            $return['msg'] = '没有该服务';
            $return['code'] = '1001';
        }
        return $return;
	}
	function ali_pay(Request $request)
	  {
	      require_once '../app/alipay/aop/AopClient.php';
	     
	      $notify_url =  "https://e.shidaichuxing.com/api/sorder/notify";
	      $money = sprintf("%.2f",$request['money']);
	      $uid = $uid = $request->get('id'); ;
	       $trade_no = $uid . date('YmdHis',time()).rand(1111,9999);
	       $arr = [
	            'money'=>$money,
	            'source'=>0,
	            'source_id'=>$uid,
	            'pay_way'=>2,
	            'created_at'=>date('Y-m-d H:i:s',time()),
	            'out_trade_no'=>$trade_no,
	            'status'=>1,
	        ];
	        Db :: table('social_recharge_log')->insert($arr);
	     
	      $c = new \AopClient;
	      $c->signType = "RSA2";
	      $c->appId = "2018052860271109";

	      //支付宝公钥
	      $c->alipayrsaPublicKey ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhiBZEEqftuHPn86HdbhcoPmrjHErcoqHfhB25vk1kjmPlA5ovytISqsJZnV9JKSY+vQ53ITL/RpQjLKFmqjqZGm5GzOD2Q1Yfzacfptm8vFA2cZcjJ5sr4CXcYf56yq7YXX3JoGwSPlMzs9LJYXd5N/GRpwLHXNx+9eMCX31N+emCGwItJTIWjRk7F7Oq5YT2O/4nSw1XLce4GBKAkK/iDk0bBE6BHdAVLMnfOs26f/0hNCNkqiTSBekCIvKoy1PuXgEoxRVec7gVc+9IGZgGcROX6RN1qsOLIfsU74/6Sl7CTcn6Y4cjBerfskVDqCFDsoB3yUfU0KXhBhdd4+MDwIDAQAB";
	      
	      //应用秘钥
	      $c->rsaPrivateKey ="MIIEogIBAAKCAQEApv0/3UzexQ6b827W/zYYeAAqiXAO/KHrJfdIZbazHshOpLdIIrk9XFZXGI+bZlgPFaTZsiyOidhjUj2NIx/uz3IW2d128e2EbUz5qs7DlhkZ3KvBcRRDGTgxUUaJHrail866VXZEyDPihmApz6lV2Tsyx712FroDfxnE1OB4rSOby/1BWuHTRrE5Zsv+2K8QfRDUOaiM5dcKjYe5CIJJbnXUYf5QoKdwEGd37Ao3be04+sQnRUsS7qh/egJRLQgOgbXGwZBaq7PRzarg3zsfdxsw5wfZbLerfwYsnEGdVR5GOBnRIPqNFnOWyZok+coJ3PD21v9UrKIss5XxStyrYwIDAQABAoIBAHuuPssN0EFrnJ4kjiDgVCctGFRLJw5+bsfj6z9KnkhCW90r0sXFJWlqmX+bfaHDvwhs3MBWuAvotUeIRyyozhvfiIU8vohZPyglRxX3pm1ZkgobPF8gfsIDGKP19kFFTA/cEa6StkcCBtk4CD/CT89hRS8jaH9UrppI37w7taWl85gBEmiQSjRYVZg1YjxIj6RY/ucbvwIlOzhQMvo/3kUJQ4vep16e/vbuFCi5boMGt/PXlWUh+HDqmYqnrE1WpCITHRL+jmYgK2li/oj985X//ZxkGTWSash8wWWD8RDOK7KAqOeJ6Bdy3DWI+DZA7flPIe/P/rdlr4DWWHcs9kECgYEA1mgqLyLhWL0irqkHwNGWtgTg6u/30oaQJWC/VYVv/JLCcKOIG2JjuGYpm2rn8PAsSOqmDkdfhTlLWEW5CqPG71E0NmkHb4eYMQ+ryEx+HXvq3Vo386fE/OFmy8jz6QW3ruQr586PYMfARW9sFy9CWbDoyfVKywwFVrjt5iO1bdkCgYEAx2I9IQ/MvJXn2io0ljNBYrEvaK+iI7c0LQUP4wZApTl+++yxTUkzbEdhWYEq7cJPJrr0mGMJX//RFXS0/0okBc6lThJ6Gg4R9TPOEbz4TjjwYu1ROoucay11IlO6nADtefAETCJz3dggFzBBhCo3Kdzv6zyI0DfDbR5iH+Hd0ZsCgYAQwpXBl4VsDWTfqGDtxrR0SA9Y7ic+Mryj31s1kTe+064VZgMmuNs4t+u6tXGqGOwtSwJuDVA/NspX/SNI3KKZZIyjUDR/mGbiNupjvu8A2QX0BbBoAI5agjgp5+yBI6xHJJj2BuSYWSUDiIE3kr8qCbU4zE7rbmYgcFZQbiwpiQKBgFPNrNfqpilV8L+4IaZIIOF0i/K6b7IHXPzXNdg8Voub4Q3ObK+JZv3J+tb9/ac1lsM2rXwnlFcvVRhpl3H+Han7M2vfREcTRuUDQ0gdX1ixgghyq0OqTrKVxrgI7VSI50frZEMD8CN8pfBZLhB5FfqYjJcZOIAcEB4bOS8hZnSlAoGAf1sevv2FBMZ57YQcAbtw0AaudV8FNlv+Oj6w2RN6Q8/P11ihpFS6lZ7wDEaipjJxYo0t0DgLlIMPf1n4QVowewBJFHHTx7YaD6mPnPIB38JZ6+Av0G3AxUugW+GNJReNLXfScSOgbAB5PpyKDdovRo4DCogHtGYf/ymqjIWkqsM=";

	      $content['subject'] = '时代出行支付';//商品的标题/交易标题/订单标题/订单关键字等。
	    
	     
	    
	      $content['out_trade_no'] = $trade_no;//商户网站唯一订单号
	      $content['total_amount'] =$money;//    订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]，
	      $content['product_code'] = "QUICK_MSECURITY_PAY";//    销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
	      $con = json_encode($content);//$content是biz_content的值,将之转化成字符串
	      $param = array();
	      $param['app_id'] = $c->appId;//支付宝分配给开发者的应用ID
	      $param['method'] = 'alipay.trade.app.pay';//接口名称
	      $param['charset'] = 'utf-8';//请求使用的编码格式
	      $param['sign_type'] = 'RSA2';//商户生成签名字符串所使用的签名算法类型
	      $param['timestamp'] = date("Y-m-d H:i:s");//发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"
	      $param['version'] = '1.0';//调用的接口版本，固定为：1.0
	      $param['notify_url'] = $notify_url;//支付宝服务器主动通知地址
	      $param['biz_content'] = $con;//业务请求参数的集合,长度不限,json格式
	      //生成签名
	      $paramStr = $c->getSignContent($param);
	      $sign = $c->alonersaSign($paramStr,$c->rsaPrivateKey,'RSA2');
	      $param['sign'] = $sign;
	      $result = $c->getSignContentUrlencode($param);//返回给客户端
	     // dump($result);
	      $arr = ['key'=>$result];
	      $arr['num'] = $trade_no;
	      $arr['money'] = $money;
	      $arr['code'] = '1000';
	      //$a = json_encode($result);
	      //dump($a);
	      return json_encode($arr) ;
	  }
	//支付宝异步通知
    public function notify()
    {
    //  Db :: table('test')->insert(['test'=>1]);
    	include_once ('../app/alipay/AopSdk.php');  
     //  Db :: table('test')->insert(['test'=>2]);
  		include_once ('../app/alipay/aop/AopClient.php'); 
     //  Db :: table('test')->insert(['test'=>3]);
		//验证签名  
		$aop = new \AopClient;  
    // Db :: table('test')->insert(['test'=>$aop]);
   //  Db :: table('test')->insert(['test'=>4]);
	//	$aop->alipayrsaPublicKey = \Comm\Pay\Alipay::ALIPAY_RSA_PUBLIC_KEY;  
   //  Db :: table('test')->insert(['test'=>$aop->alipayrsaPublicKey]);
     $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhiBZEEqftuHPn86HdbhcoPmrjHErcoqHfhB25vk1kjmPlA5ovytISqsJZnV9JKSY+vQ53ITL/RpQjLKFmqjqZGm5GzOD2Q1Yfzacfptm8vFA2cZcjJ5sr4CXcYf56yq7YXX3JoGwSPlMzs9LJYXd5N/GRpwLHXNx+9eMCX31N+emCGwItJTIWjRk7F7Oq5YT2O/4nSw1XLce4GBKAkK/iDk0bBE6BHdAVLMnfOs26f/0hNCNkqiTSBekCIvKoy1PuXgEoxRVec7gVc+9IGZgGcROX6RN1qsOLIfsU74/6Sl7CTcn6Y4cjBerfskVDqCFDsoB3yUfU0KXhBhdd4+MDwIDAQAB';
    // Db :: table('test')->insert(['test'=>5]);
		$flag = $aop->rsaCheckV1($_POST, NULL, "RSA2"); 
    // Db :: table('test')->insert(['test'=>$flag]);
    
    // Db :: table('test')->insert(['test'=>6]); 
		  
		//验签  
		if($flag){  
      // Db :: table('test')->insert(['test'=>7]);
		    //处理业务，并从$_POST中提取需要的参数内容  
		    if($_POST['trade_status'] == 'TRADE_SUCCESS'  
		        || $_POST['trade_status'] == 'TRADE_FINISHED'){//处理交易完成或者支付成功的通知
         //    Db :: table('test')->insert(['test'=>8]);  
		        //获取订单号  
		        $orderId = $_POST['out_trade_no'];  
		        //交易号  
		        $trade_no = $_POST['trade_no'];  
		        //订单支付时间  
		        $gmt_payment = $_POST['gmt_payment'];  
		        //转换为时间戳  
		        $gtime = strtotime($gmt_payment);  
		  
		        //此处编写回调处理逻辑  
            Db :: table('social_recharge_log')->where('out_trade_no',$orderId)->update(['status'=>0]);
		       $re = Db :: table('social_recharge_log')->where('out_trade_no',$orderId)->first();
           $money = $re -> money;
           $uid = $re -> source_id;
           $re2 = Db :: table('social_user')->where('id',$uid)->increment('sum_money',$money);
		        //处理成功一定要返回 success 这7个字符组成的字符串，  
		        //die('success');//响应success表示业务处理成功，告知支付宝无需在异步通知  
          
            return 'success';
		          
		    }else{
            return 'failed';
        } 
    	}else{
            return 'failed';
      } 
	}
	/**
     * 模拟get请求
     * @param $url
     * @return mixed
     */
    private function get_curl_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print_r(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($result,TRUE);
    }

}